function varargout = TLAutodocDlg(action,varargin)

% TL_AUTODOC_DLG manages user interface for TargetLink autodoc customization block
%
% SYNTAX dlgInfo = TLAutodocDlg(action);
%   gets dialog info of TargetLink autodoc customization block
%
%   INPUT ARGUMENTS
%   action      'GetDlgInfo'
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims,ctrlPos] = ...
%           TLAutodocDlg(action,pageName,commonGeom,dlgfig,sheetDims,bCodeComment);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   action          'CtrlPositions'
%   pageName        name of current page
%   commonGeom      common geometrie data
%   dlgfig          handle for dialog figure
%   sheetDims       dimension of sheet
%   bCodeComment    should code comment be available
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = ...
%           TLAutodocDlg(action,pageName,dlgfig,dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   action      'Create'
%   pageName    name of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%
% SYNTAX [dlgdata,bModified] = ...
%           TLAutodocDlg(action,pageName,dlgfig,dlgdata,pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   action      'Manage'
%   pageName    name of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = ...
%           TLAutodocDlg(action,dlgfig,dlgdata,pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   action      'Update'
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageNum     number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%
% SYNTAX TLAutodocDlg(action,dlgfig,dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   action      'Apply'
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit
% $RCSfile: TLAutodocDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_UtilityBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.5 $
% $Date: 2011/07/19 09:48:47MESZ $
%
% Copyright ?2010 dSPACE GmbH. All rights reserved.


switch action
    
    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlutil');
        dlgInfo.bShowBrowser    = true;
        dlgInfo.bViewCode       = false;
        dlgInfo.bEditCode       = false;
        dlgInfo.bShowBlock      = false;
        titleName = 'Autodoc Customization';
        dlgInfo.title = sprintf('TargetLink %s', titleName);
        dlgInfo.pageNames = {
            'Parameters'};
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);
        
    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        
        switch pageName
            case 'Parameters'
                [sheetDims,ctrlPos] = FcnParametersCtrlPositions(commonGeom);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;
        
    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName,dlgdata.pageNames,'exact');
        switch pageName
            case 'Parameters'
                dlgdata = FcnCreateParametersPage(pageNum,dlgfig,dlgdata);
        end
        % overwrite bLocked, because main data cannot be written for libraries
        dlgdata.bLocked = strcmpi(get_param(bdroot(dlgdata.model), 'BlockDiagramType'), 'Library');
        % update ok systembutton
        set(dlgdata.SystemButtons.Close, 'Enable', flag2str(~dlgdata.bLocked));
        % update status label
        if dlgdata.bLocked
            statusStr = 'Block data cannot be modified due to library lock.';
        else
            statusStr = 'Ready';
        end
        set(dlgdata.SystemButtons.StatusLabel, 'String',statusStr);
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;
        
    case 'Manage',
        pageName   = varargin{1};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName,dlgdata.pageNames,'exact');
        
        switch pageName
            case 'Parameters'
                [dlgdata, bModified] = FcnManageParametersPage(pageNum,dlgdata,pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified;
        
    case 'Update'
        dlgfig   = varargin{1};
        dlgdata  = varargin{2};
        pageNum  = varargin{3};
        pageName = dlgdata.pageNames{pageNum};
        switch pageName
            case 'Parameters'
                dlgdata = FcnUpdateParametersPage(pageNum, dlgfig, dlgdata);
        end
        varargout{1} = dlgdata;
        
    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;
        
    otherwise
        error(['Invalid action ''' action '''']);
        
end


%-------------------------------------------------------------------------------
% FcnParametersCtrlPosition calculates positions of blockspecific controls of parameters page.
%   Positions are calculated from the bottom left of the fig to avoid dependencies on figure size.
%
% INPUT ARGUMENTS
%   commonGeom      common geometries like text height, ...
%
% OUTPUT ARGUMENTS
%   ctrlPos         position of the controls
%   sheetDims       total sheetDims of all controls ([width height])
%-------------------------------------------------------------------------------
function [sheetDims,ctrlPos] = FcnParametersCtrlPositions(commonGeom)

strings_and_styles = { ...
    repmat('m',1,50),                                               'edit'; ...
    'Enter text to be inserted into generated documentation',       'text'; ...
    'Add screen copy of Simulink subsystem or SF chart/subchart',   'checkbox'; ...
    repmat('m',1,48),                                               'popupmenu'};

[parametersEditSize, ...
    parametersLabelSize, ...
    parametersCheckboxSize, ...
    parametersPopupSize] = ...
    ds_get_uicontrol_sizes(commonGeom,strings_and_styles);

widths = parametersEditSize(1);
[col,colWidth,colDelta,rowDelta] = ds_get_gui_columns(widths,commonGeom);

parametersGroupboxWidth = col(end) + ...
    colWidth(end) + ...
    commonGeom.frameSideEdgeBuffer;
parametersGroupboxHeight = ...
    commonGeom.frameTopEdgeBuffer + ...
    8 * rowDelta + ...
    16 * commonGeom.editHeight + ...
    commonGeom.frameBottomEdgeBuffer;

cx = commonGeom.figSideEdgeBuffer + commonGeom.sheetSideEdgeBuffer;
cy = commonGeom.bottomSheetOffset + ...
    commonGeom.sheetBottomEdgeBuffer;
ctrlPos.parametersGroupbox = [cx cy parametersGroupboxWidth parametersGroupboxHeight];

cx = col(1);
cy = commonGeom.frameBottomEdgeBuffer;

% documentation hook popup
ctrlPos.documentationHookPopup = [cx cy parametersPopupSize];

cy = cy + commonGeom.editHeight;
ctrlPos.documentationHookLabel = [cx cy parametersLabelSize];

% chart popup
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.chartPopup = [cx cy parametersPopupSize];
cy = cy + commonGeom.editHeight;
ctrlPos.chartLabel = [cx cy parametersLabelSize];

cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.texticonCheckbox = [cx cy parametersCheckboxSize];
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.screenCopyCheckbox = [cx cy parametersCheckboxSize];
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.newChapterCheckbox = [cx cy parametersCheckboxSize];

% text edit
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.textEdit = [cx cy parametersEditSize(1) 7*parametersEditSize(2)];

cy = cy + 7*commonGeom.editHeight;
ctrlPos.textLabel = [cx cy parametersLabelSize];

% caption edit
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.captionEdit = [cx cy parametersEditSize];

cy = cy + commonGeom.editHeight;
ctrlPos.captionLabel = [cx cy parametersLabelSize];

width = ...
    parametersGroupboxWidth + ...
    2 * commonGeom.frameSideEdgeBuffer;
height = ...
    parametersGroupboxHeight ...
    + commonGeom.editHeight;

sheetDims = [width height];


%-------------------------------------------------------------------------------
% FcnCreateParametersPage creates parameters page. Edit fields and checkboxes are left
%   empty, they are filled out with the block data in the update function
%
% INPUT ARGUMENTS
%   pageNum     number of the page
%   dlgfig      handle of dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     dialog data
%-------------------------------------------------------------------------------
function dlgdata = FcnCreateParametersPage(pageNum,dlgfig,dlgdata)

ctrlPos = dlgdata.pageData{pageNum}.ctrlPos;

enumStruct = tl_manage_blockset('GetEnums');
idx = strcmp({enumStruct.name},'DocumentationHookEnum');
documentationHookEnums = enumStruct(idx).strings; 

Children.parametersGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {''}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.parametersGroupbox);

Children.captionLabel = uicontrol( ...
    'Parent',             Children.parametersGroupbox, ...
    'String',             'Caption', ...
    'Style',              'text', ...
    'Position',           ctrlPos.captionLabel);

Children.captionEdit = uicontrol( ...
    'Parent',             Children.parametersGroupbox, ...
    'String',             'Caption', ...
    'BackGroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.captionEdit);

Children.textLabel = uicontrol( ...
    'Parent',             Children.parametersGroupbox, ...
    'String',             'Enter text to be inserted into generated documentation', ...
    'Style',              'text', ...
    'Position',           ctrlPos.textLabel);

Children.textEdit = uicontrol( ...
    'Parent',             Children.parametersGroupbox, ...
    'String',             'Text', ...
    'BackGroundColor',    'w', ...
    'Min',                0, ...
    'Max',                2, ...
    'Style',              'edit', ...
    'Position',           ctrlPos.textEdit);

Children.newChapterCheckbox = uicontrol( ...
    'Parent',             Children.parametersGroupbox, ...
    'Style',              'checkbox', ...
    'Value',              0, ...
    'String',             'Add as a new chapter', ...
    'Position',           ctrlPos.newChapterCheckbox );

Children.screenCopyCheckbox = uicontrol( ...
    'Parent',             Children.parametersGroupbox, ...
    'Style',              'checkbox', ...
    'Value',              0, ...
    'String',             'Add screen copy of Simulink subsystem or SF Chart/Subchart', ...
    'Position',           ctrlPos.screenCopyCheckbox );

Children.texticonCheckbox = uicontrol( ...
    'Parent',             Children.parametersGroupbox, ...
    'Style',              'checkbox', ...
    'Value',              0, ...
    'String',             'Display text on block icon', ...
    'Position',           ctrlPos.texticonCheckbox );

Children.chartLabel = uicontrol( ...
    'Parent',             Children.parametersGroupbox, ...
    'String',             'Associate with SF Chart/Subchart', ...
    'Style',              'text', ...
    'Position',           ctrlPos.chartLabel);

Children.chartPopup = uicontrol( ...
    'Parent',             Children.parametersGroupbox, ...
    'String',             {''}, ...
    'Value',              1, ...
    'BackGroundColor',    'w', ...
    'Style',              'popupmenu', ...
    'Position',           ctrlPos.chartPopup);

Children.documentationHookLabel = uicontrol( ...
    'Parent',             Children.parametersGroupbox, ...
    'String',             'Documentation placement', ...
    'Style',              'text', ...
    'Position',           ctrlPos.documentationHookLabel);

Children.documentationHookPopup = uicontrol( ...
    'Parent',             Children.parametersGroupbox, ...
    'String',             documentationHookEnums, ...
    'Value',              1, ...
    'BackGroundColor',    'w', ...
    'Style',              'popupmenu', ...
    'Position',           ctrlPos.documentationHookPopup);

dlgdata.pageData{pageNum}.children = Children;

% set tooltip strings
set_tooltipstrings(dlgdata.pageData{pageNum}.children);


%-------------------------------------------------------------------------------
% FcnManageParametersPage manages option page.
%
% INPUT ARGUMENTS
%   pageNum     number of the page
%   dlgdata     dialog data
%   action      depending on the field that has been edited
%
% OUTPUT ARGUMENTS
%   dlgdata     dialog data
%   bModified   flag = 1, if data has been modified, =0 otherwise
%-------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageParametersPage(pageNum, dlgdata, action)

% default return value
bModified = false;  %#ok
Children = dlgdata.pageData{pageNum}.children;
data = dlgdata.data.autodoc;

switch action
    case 'captionEdit'
        data.caption = deblank(get(Children.captionEdit,'String'));
        bModified = true;
        
    case 'textEdit'
        data.text = cellstr(deblank(get(Children.textEdit,'String')));
        bModified = true;
        
    case 'newChapterCheckbox'
        data.newchapter = get(Children.newChapterCheckbox,'Value');
        bModified = true;
        
    case 'screenCopyCheckbox'
        data.screencopy = get(Children.screenCopyCheckbox,'Value');
        bModified = true;
        
    case 'texticonCheckbox'
        data.displaytextonicon = get(Children.texticonCheckbox,'Value');
        bModified = true;
        
    case 'chartPopup'
        chartValue = get(Children.chartPopup, 'Value');
        if chartValue == 1
            data.selectedchart = '';
        else
            chartStrings = get(Children.chartPopup, 'String');
            data.selectedchart = chartStrings{chartValue};
        end
        bModified = true;
        
    case 'documentationHookPopup'
        hookValue = get(Children.documentationHookPopup, 'Value');
        data.documentationhook = hookValue;
        bModified = true;
        
    otherwise
        error(['Invalid control ' action]);
        
end % switch(action)
dlgdata.data.autodoc = data;


%-------------------------------------------------------------------------------
% FUNCTION DESCRIPTION
%   FcnUpdateParametersPage(dlgfig,dlgdata,pageNum)
%   Function to to update controls on parameters page: enable/disable controls,
%   write data to edit fields, highlight invalid/inconsistent data.
%   Function is called after FcnCreateParametersPage and by FcnManageParametersPage in
%   case the dialog has to be updated due to new data
%
% INPUT ARGUMENTS
%   pageNum     Number of page
%   dlgfig      Handle of dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     dialog data
%-------------------------------------------------------------------------------
function dlgdata = FcnUpdateParametersPage(pageNum,dlgfig,dlgdata)

data = dlgdata.data.autodoc;
Children = dlgdata.pageData{pageNum}.children;

if dlgdata.bIsFullVs
    IsFullVsON = 'on';
else
    IsFullVsON = 'inactive';
end

captionEditCtrlStatus = struct('enable', IsFullVsON);
textEditCtrlStatus = struct('enable', IsFullVsON);
newChapterCheckboxCtrlStatus = struct('enable', IsFullVsON);
screenCopyCheckboxCtrlStatus = struct('enable', IsFullVsON);
texticonCheckboxCtrlStatus = struct('enable', IsFullVsON);
chartPopupCtrlStatus = struct('enable', IsFullVsON, ...
    'string', {get(Children.chartPopup, 'String')}, ...
    'value', 1);
documentationHookPopupCtrlStatus = struct('enable', IsFullVsON, ...
    'string', {get(Children.documentationHookPopup, 'String')}, ...
    'value', 1);

% Get the names of the charts and subcharts residing in the subsystem
% a current autodoc customization block is located
selectChartEntries = {};
modelName          = get_param(bdroot(dlgdata.model),'Name');
if exist('sf','file') == 3,
    hSubsystem = get_param(dlgdata.model, 'Parent');
    hChartList = [tl_get_sfobjects(hSubsystem,'SFChart') tl_get_emlobjects(hSubsystem, 'EMLFunction')];
    for i = 1:length(hChartList),
        [path, name] = fileparts(sf('get',hChartList(i),'.name'));
        if isempty(path) && tl_is_valid_incr_system(modelName)
            % charts resided in ref. model
            fullPath = modelName;
        else
            fullPath = [modelName '/' path];
        end
        if strcmp(fullPath, hSubsystem),
            selectChartEntries{end+1} = strrep(name, char(10), ' '); %#ok<AGROW>
            
            % now search for subcharts
            sfver = ver('stateflow');
            if ~isempty(sfver),
                % sf is installed
                hSubChartList = sf('SubchartsIn',hChartList(i));
                if ~isempty(hSubChartList),
                    chartName = selectChartEntries{end};
                    selectChartEntries{end+1} = [chartName ' (with subcharts)']; %#ok<AGROW>
                    selectChartEntries{end+1} = [chartName ' (subcharts only)']; %#ok<AGROW>
                end
                for j = 1:length(hSubChartList),
                    % get the chart/subChart name
                    subChartName = sf('get',hSubChartList(j),'.name');
                    hParent      = sf('get',hSubChartList(j),'.treeNode.parent');
                    while hParent ~= 0,
                        subChartName = [sf('get', hParent, '.name') '.' subChartName]; %#ok<AGROW>
                        hParent      = sf('get',hParent, '.treeNode.parent');
                    end
                    idx = find(subChartName == '/');
                    if ~isempty(idx),
                        subChartName = subChartName(idx(end)+1:end);
                    end
                    selectChartEntries{end+1} = strrep(subChartName,char(10), ' '); %#ok<AGROW>
                end
            end
        end
    end
end
if isempty(selectChartEntries),
    selectChartEntries{1} = 'none';
    bChartEnable = 'off';
else
    selectChartEntries = [...
        {'none' } ...
        selectChartEntries];
    bChartEnable = IsFullVsON;
end

captionEditCtrlStatus.string = data.caption;
textEditCtrlStatus.string = data.text;
newChapterCheckboxCtrlStatus.value = data.newchapter;
screenCopyCheckboxCtrlStatus.value = data.screencopy;
texticonCheckboxCtrlStatus.value = data.displaytextonicon;
chartPopupCtrlStatus.value = find(strcmp(data.selectedchart, selectChartEntries));
if isempty(chartPopupCtrlStatus.value)
    chartPopupCtrlStatus.value = 1;
end
chartPopupCtrlStatus.string = selectChartEntries;
chartPopupCtrlStatus.enable = bChartEnable;
documentationHookPopupCtrlStatus.value = data.documentationhook;

% set control status
ctrlsList = { ...
    'captionEdit' ...
    'textEdit' ...
    'newChapterCheckbox' ...
    'screenCopyCheckbox' ...
    'texticonCheckbox' ...
    'chartPopup' ...
    'documentationHookPopup'};

% write back control status of controls to the controls' UserData property
for ctrlsNo = 1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end

% set control status of table parameter groupbox controls
TLSetCtrlsStatus(dlgfig, Children, ctrlsList)
% end of function FcnUpdateParametersPage
